import { reactive, defineComponent, ref, onMounted, onUnmounted } from "vue";
import { Modal, message, Skeleton } from "ant-design-vue";
// import docx from "docx-preview";
// import mammoth from "./m";
import "./style.less";
import { isNil } from "lodash-es";
import { validateFileType } from "./validate";
import Word from "./word";
import { pushListener, removeListener } from "./display";
import DocPreview from "./doc";




// 获取名称
const parserFileFullName = (url: string): [string, string] => {
  const suffixIndex = url.lastIndexOf(".");

  if (suffixIndex === -1) {
    return null;
  }

  const suffixName = url.slice(suffixIndex , url.length);

  const nameIndex = url.lastIndexOf("/", suffixIndex);
  const fileName = url.slice(nameIndex + 1, suffixIndex);

  return [fileName, suffixName];
};

// 加载为html

const ViewWord = defineComponent({
  setup(props, ctx) {
    const cacheState = new Map<string, ArrayBuffer>();
    const viewRef = ref(null);
    const remote = reactive({
      title: null,
      opts: {},
      wordRemoteUrl: null,
      // 可能需要一个枚举更好
      type: null
    });

    const viewState = reactive({
      wordHtml: null,
      width: 700,
      current: {
        suffixName: null,
        fileName: null
      },
      loading: false,
      visibility: false,
      errorMessage: null
    });

    const complete = () => {
      viewState.loading = false;
    };

    const listenOfModalCancel = () => {
      remote.title = null;
      viewState.visibility = false;
    };

    const display = (
      url: string,
      options?: Dict<any>
    ) => {
      // 获取url中的名称和后缀名
      const parserd = parserFileFullName(url);
      // / 因为获取不到文件名，不是一个静态文件，可能是服务器流文件，放弃
      if (parserd === null) {
        message.warning("对不起，该文件暂时不支持预览");
        return;
      }

      const [fileName, ext] = parserd;

      // todo: 文件不支持时是否支持下载
      if (!validateFileType(ext)) {
        message.warning("对不起，该文件暂时不支持预览");
        return;
      }

      const hasCache = cacheState.has(url + fileName + ext);

      viewState.current.fileName = fileName;
      viewState.current.suffixName = ext;
      viewState.width = document.body.clientWidth - (document.body.clientWidth / 4);

      remote.wordRemoteUrl = url;
      if (!isNil(options)) {
        if (!isNil(options.title)) {
          remote.title = options.title;
        }
        remote.opts = options;
      }

      viewState.visibility = true;
      if (!hasCache) {
        viewState.loading = true;
      }


      // // 开启loading
      // schedulerCallbackOnNextLongTick(() => {
      //   /// 缓存中存在直接设置返回
      //   if (hasCache) {
      //     pushHtml(viewRef.value, cacheBuffer.get(url + fileName + ext));
      //     return;
      //   }

      //   loadWordHtml(options);
      // });
    };

    onMounted(() => {
      pushListener(display);
      onUnmounted(() => {
        removeListener(display);
      });
    });
    ctx.expose({
      display: display,
      validateFileType
    });

    function getPreviewWidgets(type: string): JSX.Element {
      switch (type) {
        case ".doc":
          return <DocPreview
            cache={cacheState}
            options={remote.opts}
            url={remote.wordRemoteUrl}
            visibility={viewState.visibility}
            fileName={viewState.current.fileName}
            ext={viewState.current.suffixName}
            onComplete={complete}
          />;
        case ".docx":
          return <Word
            cache={cacheState}
            visibility={viewState.visibility}
            url={remote.wordRemoteUrl}
            fileName={viewState.current.fileName}
            ext={viewState.current.suffixName}
            onComplete={complete}
          />;

        default:
          return <div>暂不支持的文件类型</div>;
      }
    }



    return () => {
      const node = getPreviewWidgets(viewState.current.suffixName);

      return <Modal onCancel={listenOfModalCancel} onOk={listenOfModalCancel} bodyStyle={{ minHeight: "calc(100vh - 260px)" }} width={viewState.width} title={remote.title !== null ? remote.title : "预览word文档"} v-model:visible={viewState.visibility} >
        {
          viewState.loading
            ? <Skeleton />
            : null
        }
        <section class="view-word-wrap" style={viewState.loading ? { display: "none" } : { display: "block" }}>
          <section ref={viewRef} class="view-inner-word">
            {node}
          </section>
        </section>
      </Modal>;
    };
  }
});

export default ViewWord;
